Refactor useDebounce hook for better readability#1
Merged
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Related Issue
Description
🧱 The Architectural Context:
React components execute updates dynamically based on continuous state adjustments. If an asynchronous micro-task (like a network fetch or a
setTimeoutclock) finishes processing after its parent component has already unmounted from the DOM, triggering a state setter function causes a severe memory leak warning in the browser console.❌ The Failure Mechanism:
The original
useDebouncehook initialized asetTimeoutscheduler every time a character was typed into a search input. If a user typed a character and immediately clicked a navigation link to change pages before the delay timer finished, the component tree unmounted, but the background browser timer remained active in the event loop. Once the timer completed, it attempted to callsetDebouncedValue(value).💥 The Impact:
This triggered the classic React runtime warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak. In larger applications, thousands of these uncleaned micro-tasks degrade client-side performance, exhaust system memory, and cause sluggish UI responses.
✅ The Solution:
Integrated a persistent tracking reference pointer using
useRef(true)alongside an explicit cleanup routine. This ensures that the component safely clears any remaining background timer threads viaclearTimeoutand flags the tracking node asfalsethe exact millisecond the component unmounts, preventing unmounted state state adjustments entirely.Type of Change